#!/bin/bash
#
# apnsrpcd        Startup script for apnsrpcd
#
# chkconfig: - 99 03
# description: Apnsrpcd is a service to send messages to the Apple Push Notification Service 
# processname: apnsrpcd.py
# config: /usr/local/apnsrpcd/etc/apnsrpcd.conf
# pidfile: /usr/local/apnsrpcd/etc/apnsrpcd.pid


. /etc/rc.d/init.d/functions

PREFIX="/usr/local/apnsrpcd"
BIN="$PREFIX/bin/apnsrpcd.py"
CONF="$PREFIX/etc/apnsrpcd.conf"
PIDFILE="$PREFIX/etc/apnsrpcd.pid"

start(){
	echo -n 'Starting apnsrpcd...'
	if [ -f "$PIDFILE" ]; then
		PID="$(cat $PIDFILE)"
		if kill -0 "${PID}" >/dev/null 2>&1; then
			echo_failure
			echo "apnsprcd is already running (PID: $PID)"
			return 1
		else
			rm -f "${PIDFILE}"
		fi
	fi

	OUTPUT="$($BIN -c $CONF)"
	if [ $? -eq 0 ]; then
		echo_success; echo ""
		return 0
	else
		echo ""
		echo "$OUTPUT"
		echo_failure; echo ""
		return 1
	fi
}

stop(){
	echo -n 'Stopping apnsrpcd...'
	if [ -f "$PIDFILE" ]; then
		PID="$(cat $PIDFILE)"
		kill "$PID" >/dev/null 2>&1
		if [ $? -eq 0 ]; then
			tries=5
			while [ $tries > 0 ]; do
				if kill -0 $PID >/dev/null 2>&1; then
					sleep 1
					((tries--))
				else
					break
				fi
			done
			if [ $tries -eq 0 ]; then
				kill -9 $PID >/dev/null 2>&1
			fi
			if kill -9 $PID >/dev/null 2>&1; then
				echo -n "Could not stop apnsrpcd (PID: $PID)"
				echo_failure; echo ""
				return 1
			fi
		fi
	fi
	echo -n 'Stopped'
	echo_success; echo ""
	return 0
}

restart(){
	stop
	start
}

status(){
	if [ -f "$PIDFILE" ]; then
		PID="$(cat $PIDFILE)"
		if kill -0 "$PID" >/dev/null 2>&1; then
			echo "apnsrpcd is running (PID: $PID)"
			return 0
		else
			echo "apnsrpcd is not running, but $PIDFILE exists"
			return 1
		fi
	else
		echo "apnsrpcd is not running"
		return 3
	fi
}

case "$1" in
        start)  
                start
                ;;
        
        stop)   
                stop
                ;;
        
        restart)
                restart
                ;;
        
        status) 
                status
                ;;
        *)      
                echo "Usage $0 {start|stop|status|restart}"

    
esac

